package com.jzo2o.foundations.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.enums.ServeHotStatusEnum;
import com.jzo2o.foundations.mapper.RegionMapper;
import com.jzo2o.foundations.mapper.ServeItemMapper;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.domain.Serve;
import com.jzo2o.foundations.model.domain.ServeItem;
import com.jzo2o.foundations.model.domain.ServeType;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.service.IServeService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * @Author Ms.发发
 * @ClassName ServeServiceImpl
 * @Date 2025/3/20 13:37
 * @Description
 **/
@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {

    @Override
    public PageResult<ServeResDTO> page(ServePageQueryReqDTO servePageQueryReqDTO) {
        PageResult<ServeResDTO> serveResDTOPageResult = PageHelperUtils.selectPage(
                servePageQueryReqDTO,
                () -> baseMapper.queryServeListByRegionId(servePageQueryReqDTO.getRegionId()));
        return serveResDTOPageResult;
    }

    @Resource
    private ServeItemMapper serveItemMapper;

    @Override
    public void putOnShelf( Long id) {
        //查询区域服务
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isNull(serve)) {
            throw new ForbiddenOperationException("区域服务不存在");
        }
        //查看状态  （上架 1 下架2 草稿0）
        Integer saleStatus = serve.getSaleStatus();
        //当区域服务的状态为草稿状态或下架状态时方可上架。
        if (!(FoundationStatusEnum.INIT.getStatus() == saleStatus || FoundationStatusEnum.DISABLE.getStatus() == saleStatus)) {
            throw new ForbiddenOperationException("草稿或下架状态方可上架");
        }
        //服务项的一个校验
        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        if (ObjectUtil.isNull(serveItem)) {
            throw new ForbiddenOperationException("服务项不存在");
        }
        //服务项的状态为启用状态时方可上架
        if (FoundationStatusEnum.ENABLE.getStatus() != serveItem.getActiveStatus()) {
            throw new ForbiddenOperationException("服务项状态为启用方可上架");
        }
        //上架
        LambdaUpdateWrapper<Serve> updateWrapper = Wrappers.<Serve>lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus());
        boolean updateFlag = update(updateWrapper);
        if(!updateFlag){
            throw new ForbiddenOperationException("上架失败");
        }
    }

    @Override
    public void takeOffShelf(Long id) {
        //查询区域服务
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isNull(serve)) {
            throw new ForbiddenOperationException("区域服务不存在");
        }
        //查看状态  （上架 1 下架2 草稿0）
        Integer saleStatus = serve.getSaleStatus();
        //当区域服务的状态为上架状态方可下架。
        if (!(FoundationStatusEnum.ENABLE.getStatus() == saleStatus)) {
            throw new ForbiddenOperationException("上架状态方可下架");
        }
        //下架
        LambdaUpdateWrapper<Serve> updateWrapper = Wrappers.<Serve>lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.DISABLE.getStatus());
        boolean updateFlag = update(updateWrapper);
        if(!updateFlag){
            throw new ForbiddenOperationException("下架失败");
        }
    }

    @Override
    public void deleteById(Long id) {
        //查询服务类型
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isNull(serve)) {
            throw new ForbiddenOperationException("区域服务不存在");
        }
        //校验状态
        Integer saleStatus = serve.getSaleStatus();
        //草稿状态方可删除
        if (!(FoundationStatusEnum.INIT.getStatus() == saleStatus)) {
            throw new ForbiddenOperationException("草稿状态方可删除");
        }
        int deleteRow = baseMapper.deleteById(id);
        if(deleteRow!=1){
            throw new ForbiddenOperationException("删除失败");
        }
    }

    @Override
    public void onHot(Long id) {
        //查询服务类型
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isEmpty(serve)) {
            throw new ForbiddenOperationException("区域服务不存在");
        }
        //校验状态  ？  TODO： 是否需要校验状态？
        //判断是否热门
        if (serve.getIsHot().equals(ServeHotStatusEnum.HOT.getStatus())) {
            throw new ForbiddenOperationException("已设置热门");
        }
        //设置热门
        LambdaUpdateWrapper<Serve> updateWrapper = Wrappers.<Serve>lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getIsHot, ServeHotStatusEnum.HOT.getStatus())
                        .set(Serve::getHotTimeStamp, System.currentTimeMillis());
        boolean updateFlag = update(updateWrapper);
        if (!updateFlag) {
            throw new ForbiddenOperationException("设置热门失败");
        }
    }

    @Override
    public void offHot(Long id) {
        //查询服务类型
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isEmpty(serve)) {
            throw new ForbiddenOperationException("区域服务不存在");
        }
        //判断是否热门
        if (serve.getIsHot().equals(ServeHotStatusEnum.NOTHOT.getStatus())) {
            throw new ForbiddenOperationException("已取消热门");
        }
        //取消热门
        LambdaUpdateWrapper<Serve> updateWrapper = Wrappers.<Serve>lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getIsHot,ServeHotStatusEnum.NOTHOT.getStatus())
                .set(Serve::getHotTimeStamp,null);
        boolean updateFlag = update(updateWrapper);
        if (!updateFlag) {
            throw new ForbiddenOperationException("取消热门失败");
        }
    }

    @Override
    public void updatePrice(Long id, BigDecimal price) {
        //判断是否存在该区域服务
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isEmpty(serve)) {
            throw new ForbiddenOperationException("区域服务不存在");
        }
        if (price.compareTo(BigDecimal.ZERO) < 0) {
            throw new ForbiddenOperationException("价格必须大于0");
        }
        //修改价格
        LambdaUpdateWrapper<Serve> updateWrapper = Wrappers.<Serve>lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getPrice, price);
        boolean updateFlag = update(updateWrapper);
        if (!updateFlag) {
            throw new ForbiddenOperationException("修改价格失败");
        }
    }


    @Resource
    private RegionMapper regionMapper;
    @Override
    public void batchAdd(List<ServeUpsertReqDTO> serveUpsertReqDTOList) {
        //校验列表数据是否为空
        if (ObjectUtil.isEmpty(serveUpsertReqDTOList)) {
            throw new ForbiddenOperationException("区域服务列表不能为空");
        }
        //批量新增
        serveUpsertReqDTOList.forEach(serveUpsertReqDTO -> {
            Serve serve = BeanUtil.copyProperties(serveUpsertReqDTO, Serve.class);
            //看该服务项是否存在
            LambdaQueryWrapper<Serve> queryWrapper = Wrappers.<Serve>lambdaQuery()
                    .eq(Serve::getRegionId, serveUpsertReqDTO.getRegionId())
                    .eq(Serve::getServeItemId, serveUpsertReqDTO.getServeItemId());
            Serve selectServe = getOne(queryWrapper);
            if (ObjectUtil.isNotEmpty(selectServe)) {
                throw new ForbiddenOperationException("该服务项已存在");
            }

            //校验服务项的状态
            ServeItem serveItem = serveItemMapper.selectById(serveUpsertReqDTO.getServeItemId());
            if(ObjectUtil.isEmpty(serveItem)){
                throw new ForbiddenOperationException("区域服务列表中存在不存在的服务项");
            }
            if(serveItem.getActiveStatus().equals(FoundationStatusEnum.DISABLE.getStatus())){
                throw new ForbiddenOperationException("区域服务列表中存在禁用的服务项");
            }

            //获取城市code
            Region region = regionMapper.selectById(serveUpsertReqDTO.getRegionId());
            if(ObjectUtil.isEmpty(region)){
                throw new ForbiddenOperationException("区域服务列表中存在不存在的区域");
            }
            serve.setCityCode(region.getCityCode());
            boolean save = save(serve);
            if (!save) {
                throw new ForbiddenOperationException("区域服务列表新增失败");
            }
        });
    }

}
